package net.zdreamer.geracomium.ui;

import java.util.ArrayList;
import java.util.List;

import net.zdreamer.geracomium.adapter.GeracomiumListAdapter;
import net.zdreamer.geracomium.adapter.HomepageViewPagerAdapter;
import net.zdreamer.geracomium.constant.Constant;
import net.zdreamer.geracomium.entity.GeracomiumInfos;
import net.zdreamer.geracomium.entity.GeracomiumReserveInfos;
import net.zdreamer.geracomium.myviews.CustomViewPager;
import net.zdreamer.geracomium.ui.home.SearchActivity;
import net.zdreamer.geracomium.utils.httputils.AssessService;
import net.zdreamer.geracomium.utils.tools_utils.URLTools;
import net.zdreamer.geracomium.utils.window.ViewControlor;

import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.geracomium.R;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class HomeFragment extends Fragment implements OnClickListener,
        OnPageChangeListener {

    int index = 0;
    List<View> advPics = new ArrayList<View>();
    List<ImageView> list_vs;// 点
    private LinearLayout DotsOnViewPager;
    private CustomViewPager customViewPager;
    private HomepageViewPagerAdapter viewPagerAdapter;
    private PullToRefreshListView geracomiumList;
    private GeracomiumInfos geracomiumInfos;
    private GeracomiumListAdapter mAdapter;
    private TextView search;
    private ImageView chahao;
    RelativeLayout layout;

    @Override
    public void onPageScrollStateChanged(int arg0) {
    }

    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {
    }

    @Override
    public void onPageSelected(int arg0) {
        customViewPager.setCurrentItem(arg0);
        initDots(list_vs.size(), arg0, true);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_home, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initViews();
        AssessService.AssessRequest(URLTools.SearchUrl, searchhandler);
    }

    /*
     * 初始化控件
     */
    private void initViews() {
        chahao = (ImageView) getActivity().findViewById(R.id.chahao1);
        search = (TextView) getActivity().findViewById(R.id.search);
        chahao.setOnClickListener(this);
        layout = (RelativeLayout) getActivity()
                .findViewById(R.id.search_layout);
        ViewControlor.setSize(getActivity(), layout, 64, 7, true);
        search.setOnClickListener(this);
        geracomiumList = (PullToRefreshListView) getActivity().findViewById(
                R.id.geracomium);
        initListView();
        new Thread(new Runnable() {

            @Override
            public void run() {
                while (true) {
                    try {
                        Thread.sleep(3000);
                        Message msg = new Message();
                        msg.what = 0;
                        handler.sendMessage(msg);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
        customViewPager.setOnPageChangeListener(this);
    }

    private void initListView() {
        GeracomiumInfos infos = new GeracomiumInfos();
        geracomiumInfos = infos;
        geracomiumList.setMode(Mode.BOTH);
        geracomiumList.setOnRefreshListener(orl);
        geracomiumList.getRefreshableView().addHeaderView(initViewPager());
        mAdapter = new GeracomiumListAdapter(getActivity(),
                geracomiumInfos.geracomiumInfos,
                R.layout.list_geracomium_detail);
        geracomiumList.getRefreshableView().setAdapter(mAdapter);
    }

    /*
     * 初始化ViewPager
     */
    private View initViewPager() {
        final View view = View.inflate(getActivity(),
                R.layout.viewpager_homepage, null);
        list_vs = new ArrayList<ImageView>();
        customViewPager = (CustomViewPager) view
                .findViewById(R.id.viewpager_homepage);
        DotsOnViewPager = (LinearLayout) view.findViewById(R.id.assss);
        viewPagerAdapter = new HomepageViewPagerAdapter(this);
        customViewPager.setAdapter(viewPagerAdapter);
        viewPagerAdapter.notifyDataSetChanged();
        ViewControlor.setSize(getActivity(), customViewPager, 12, 5, true);
        int count = viewPagerAdapter.getCount();
        initDots(count, 0, false);
        return view;
    }

    private Handler searchhandler = new Handler() {
        @TargetApi(Build.VERSION_CODES.KITKAT)
        @Override
        public void handleMessage(android.os.Message msg) {
            switch (msg.arg1) {
                case 0:
                    System.out.println(msg.obj);
                    break;

                default:
                    break;
            }

            // System.out.println(msg.objg);
        }
    };

    /*
     * 初始化Docs
     */
    private void initDots(int cc, int cur, boolean f) {
        for (int j = 0; j < cc; j++) {
            if (f) {
                if (j == cur) {
                    list_vs.get(j).setImageResource(R.drawable.page_now);
                } else {
                    list_vs.get(j).setImageResource(R.drawable.page);
                }
            } else {
                ImageView v = new ImageView(HomeFragment.this.getActivity());
                v.setPadding(3, 0, 3, 0);
                if (j == 0) {
                    v.setImageResource(R.drawable.page_now);
                } else {
                    v.setImageResource(R.drawable.page);
                }
                list_vs.add(v);
                DotsOnViewPager.addView(v);
            }
        }

    }

    private final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    index++;
                    customViewPager.setCurrentItem(index % list_vs.size());
                    break;

                default:
                    break;
            }
        }

        ;
    };


    @Override
    public void onResume() {
        super.onResume();
        ViewControlor.setSize(getActivity(), layout, 64, 7, true);
        if (Constant.SEARCH_TEXT != null) {
            chahao.setVisibility(View.VISIBLE);
            search.setBackgroundResource(R.drawable.home_search2);
            search.setText(Constant.SEARCH_TEXT);
            Constant.SEARCH_TEXT = null;
        } else {
            chahao.setVisibility(View.GONE);
            search.setBackgroundResource(R.drawable.home_search1);
            search.setText("");
        }
    }

    @Override
    public void onClick(View arg0) {
        if (arg0.equals(search)) {
            ViewControlor.setSize(getActivity(), layout, 64, 7, true);
            Intent intent = new Intent(getActivity(), SearchActivity.class);
            startActivity(intent);
        } else {
            ViewControlor.setSize(getActivity(), layout, 64, 7, true);
            chahao.setVisibility(View.GONE);
            search.setBackgroundResource(R.drawable.home_search1);
            search.setText("");
        }
    }


    OnRefreshListener2<ListView> orl = new OnRefreshListener2<ListView>() {

        @Override
        public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
            // page = 0;
            // onLoadDatas();
            String label = DateUtils.formatDateTime(getActivity()
                            .getApplicationContext(), System.currentTimeMillis(),
                    DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE
                            | DateUtils.FORMAT_ABBREV_ALL);

            refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(
                    "上次刷新：" + label);

            Thread a = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    Message message = new Message();
                    message.what = 0;
                    h.sendMessage(message);
                }
            });
            a.start();
        }

        @Override
        public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
            // page++;
            // onLoadDatas();
            String label = DateUtils.formatDateTime(getActivity()
                            .getApplicationContext(), System.currentTimeMillis(),
                    DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE
                            | DateUtils.FORMAT_ABBREV_ALL);

            refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(
                    "上次刷新：" + label);

            Thread a = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    Message message = new Message();
                    message.what = 0;
                    h.sendMessage(message);
                }
            });
            a.start();
        }
    };

    Handler h = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                GeracomiumReserveInfos infos = new GeracomiumReserveInfos();
                mAdapter = new GeracomiumListAdapter(getActivity(),
                        geracomiumInfos.geracomiumInfos,
                        R.layout.list_geracomium_detail);
                geracomiumList.setAdapter(mAdapter);
                geracomiumList.onRefreshComplete();
            }
        }
    };

}
